package com.jzy.hzit.filter;


import com.jzy.hzit.properties.SecurityGatewayProperties;
import com.jzy.hzit.util.JwtUtil;
import com.jzy.hzit.utils.ResponseUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Slf4j
public class HzitGlobalFilter implements GlobalFilter, Ordered {
	@Autowired
	private SecurityGatewayProperties gatewayProperties;
	@Autowired
	private StringRedisTemplate redisTemplate;


	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		//1. 得到白名单
		List<String> whites = gatewayProperties.getWhites();
		// 2. 得到请求地址
		// 2.1 得到请求对象
		ServerHttpResponse response = exchange.getResponse();
		ServerHttpRequest request = exchange.getRequest();
		ServerHttpRequest.Builder mutate = request.mutate();
		String path = request.getURI().getPath();
		// 2.2 判断在白名单集合中是否有此请求path
		if (whites.contains(path)) {
			return chain.filter(exchange);
		}
		// 2.3 得到请求头中的token值
		String authorization = request.getHeaders().getFirst("Authorization");
		String token = authorization.replace("Bearer ", "");

		// 2.4 解析token
		Claims claims = JwtUtil.parseToken(token);
		if(claims == null){
			return ResponseUtil.webFluxResponseWriter(response,"解析token失败！");
		}
		String uuid = claims.get("user_key") + "";

		// 2.5 得到redis的key
		String key = getKey(uuid);
		// 2.6 如果redis中有此key，证明此用户登录过
		Boolean hasKey = redisTemplate.hasKey(key);
		if(!hasKey){
			return ResponseUtil.webFluxResponseWriter(response,"登录失败！");
		}
		return chain.filter(exchange.mutate().request(mutate.build()).build());
	}

	private String getKey(String token) {
		return "login_tokens:" + token;
	}

	@Override
	public int getOrder() {
		return -100;
	}
}
